from time import sleep

import schedule as schedule
from appium import webdriver
from appium.webdriver.extensions.android.nativekey import AndroidKey
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from datetime import datetime

desired_caps = {
    'platformName': 'Android',  # 被测手机是安卓
    'platformVersion': '12',  # 手机安卓版本
    'deviceName': 'xxx',  # 设备名，安卓手机可以随意填写
    'appPackage': 'cn.com.dfitc.smartinfo',  # 启动APP Package名称
    'appActivity': 'com.dlfc.android.smartinfo.ui.activity.StartActivity',  # 启动Activity名称
    'unicodeKeyboard': True,  # 使用自带输入法，输入中文时填True
    'resetKeyboard': True,  # 执行完程序恢复原来输入法
    'noReset': True,  # 不要重置App
    'newCommandTimeout': 6000,
    'automationName': 'UiAutomator2'
    # 'app': r'd:\apk\bili.apk',
}

# 连接Appium Server，初始化自动化环境
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
# 设置缺省等待时间
driver.implicitly_wait(5)
print("----开始----")
# 等待启动
sleep(3)
# 跳过广告页
skip = driver.find_elements(By.XPATH, '//*[contains(@text, "跳过")]')
if skip:
    skip[0].click()

# def is_toast_exist(driver, text, timeout=20, poll_frequency=0.1):
#     '''
#     判断toast是否存在，是则返回True，否则返回False
#     :param driver: driver实例对象
#     :param text: toast文本
#     :param timeout: 定位超时时间
#     :param poll_frequency: 查询频率
#     :return: True or False
#     '''
#     try:
#         toast_loc = (By.XPATH, ".//*[contains(@text, %s)]" % text)
#         WebDriverWait(driver, timeout, poll_frequency).until(
#             ec.presence_of_element_located(toast_loc)
#         )
#         return True
#     except:
#         return False


# 查找元素并点击
# 通过id查找并点击
def find_click(element_id):
    ids = driver.find_elements(By.ID, element_id)
    if ids:
        ids[0].click()


# 用户协议
find_click("iv_cycle_checked")
find_click("confirm_btn")
# 首页遮罩
find_click("cn.com.dfitc.smartinfo:id/view_guide")

# 一键登录
sleep(1)
find_click("cn.com.dfitc.smartinfo:id/rl_agree_check")
find_click("cn.com.dfitc.smartinfo:id/authsdk_checkbox_view")
sleep(0.5)
find_click("cn.com.dfitc.smartinfo:id/authsdk_login_view")
sleep(1)

# 跳转行情tab
# quto = "//*[@resource-id='cn.com.dfitc.smartinfo:id/tabLayout']//android.support.v7.app.ActionBar.Tab[3]"
# driver.find_element(By.XPATH, quto).click()
driver.find_element(By.NAME, '自选').click()
sleep(1)
# 行情遮罩
find_click("cn.com.dfitc.smartinfo:id/view_guide")
sleep(3)

# 开始计时
startTime = datetime.now()
elements = driver.find_elements(By.ID, "cn.com.dfitc.smartinfo:id/tv_lastPrice")
endTime = datetime.now()
print("查找元素用时--%s" % (endTime - startTime).seconds)

lastPrice = elements[1].text
print("第一个元素的最新价->>" + lastPrice)

while "--" in lastPrice:
    sleep(0.5)
    lastPrice = elements[1].text
    print("循环时的最新价->>" + lastPrice)

endTime = datetime.now()
print("行情拉取用时--%s" % (endTime - startTime).seconds)


print('-------豆一 是否更新最新价---------')
# 行情分类
driver.find_element(By.ID, "cn.com.dfitc.smartinfo:id/title_frg_infomation").click()
sleep(1)
# 点击大商所DCE
driver.find_element(By.XPATH, "//*[@text='大商所DCE']").click()

driver.swipe(910, 300, 200, 300, 1000)
driver.swipe(910, 300, 200, 300, 1000)

# 点击豆一
tabLayouts = driver.find_elements(By.ID, "cn.com.dfitc.smartinfo:id/tabLayout")
topTab = tabLayouts[0]
tabs = topTab.find_elements(By.XPATH, ".//android.support.v7.app.ActionBar.Tab")
tabs[2].click()

douTvPricePrices = driver.find_elements(By.ID, "cn.com.dfitc.smartinfo:id/tv_lastPrice")
isUpdate = False
oldList = []
for index in range(len(douTvPricePrices)):
    print("豆一的 第 %s 个元素的最新价 ->> : %s" % (index, douTvPricePrices[index].text))
    oldList.append(douTvPricePrices[index].text)


# 检查任务 比较豆一行情新值 旧值
def job1():
    print("-----------检查任务开始-----------")
    for idx in range(len(douTvPricePrices)):
       if oldList[idx] == douTvPricePrices[idx].text:
           print("旧值 %s - 新值 %s" % (oldList[idx], douTvPricePrices[idx].text))
       else:
           print("已更新 -----  旧值 %s  --  新值 %s" % (oldList[idx], douTvPricePrices[idx].text))
           global isUpdate
           isUpdate = True


# 定时任务 每20s检查 豆一行情是否更新
schedule.every(20).seconds.do(job1)

while True:
    if isUpdate:
        # 清空定时任务
        schedule.clear()
        print("豆一行情可正常更新")
    else:
        # 运行定时任务
        schedule.run_pending()
        sleep(1)

input('**** Press to quit..')
driver.quit()

# for element in tabs:
#     print('----------------')
#     print(tabs.get_attribute('outerHTML'))

#
# dou1 = "//*[@resource-id='cn.com.dfitc.smartinfo:id/rl_item_variety]/.."
# tabs = topTab.find_element(By.XPATH, dou1)
#
# driver.find_elements_by_class_name()

# try:
#     正常的操作
#    ......................
# except:
#     发生异常，执行这块代码
#    ......................
# else:
#     如果没有异常执行这块代码


# for index in range(len(elements)):
#     print("第"+index+"个元素的的最新价-- : %s" % elements[index])

# i = 0
# while i < 50: # 循环查找的次数
# 	try:
# 		self.driver.find_element_by_xpath("xpath= 想要找到的控件").click()
# 		break
# 	except NoSuchElementException as e:
# 		swipe_to_top() #自己封装一段方法，用来实现滑动
# 		i = i + 1


# 结束计时

input('**** Press to quit..')
driver.quit()
#
# driver.find_element(By.XPATH, "//android.widget.TextView[contains(@text, '跳过']").click()

# driver.swipe(800, 800, 300, 800, 1000)
# sleep(1)
# driver.swipe(800, 800, 300, 800, 1000)
# to_all()
#
# # list = ['国内期现', '国内期权', '全球指数', '股指期货', '行业分类', '特色下单', '交易下单', '期市要闻', '快讯', '热门专题', '工业品', '贵金属']
# list = ['国内期现', '国内期权', '全球指数']
# for item in list:
#     print('当前项目: %s' % item)
#     path = "//*[@text='" + item + "']/../../.."
#     print(path)
#
#     driver.find_element(By.XPATH, path).click()
#     sleep(1)
#     back()
#     to_all()
#
# # list2 = ['现货专区', '主力排名', '实时统计', '生猪指数', '财经早报', '商品专题', '农产品']
# list2 = ['现货专区', '主力排名', '实时统计']
# for item in list2:
#     print('当前项目: %s' % item)
#     path = "//*[@text='" + item + "']/../../.."
#     print(path)
#
#     driver.find_element(By.XPATH, path).click()
#     title = driver.find_element(By.ID, "tv_name_top").text
#     assert "现货专区" in title
#     sleep(1)
#     back()
#
# path1 = "//*[@text='我的消息']/../../.."
# driver.swipe(500, 2000, 500, 200, 1000)
# try:
#     driver.find_element(By.XPATH, path1).click()
#     sleep(1)
#     back()
# except NoSuchElementException:
#     driver.swipe(500, 2000, 500, 200, 1000)
#     driver.find_element(By.XPATH, path1).click()
#     sleep(1)
#     back()
#
# input('**** Press to quit..')
# driver.quit()

#
# def swipe():
#   is_find = False  # 默认没找到元素
#
#   while is_find is not True:
#     try:
#       driver.find_element_by_xpath("//android.widget.TextView[@text='1995']").click()
#       is_find = True  # 找到了，退出循环
#     except NoSuchElementException:
#       if index == 1:
#         driver.find_element(By.XPATH, "//*[@text='国内期现']/../../..").click()
#         sleep(1)
#         back()
#      elif season == 2:
#         return "Summer"
#       elif season == 3:
#         # # 该方法调用已封装的向上滑动类
#         # self.slide.swipe_up(2500)
#         # # 所有年份，获取屏幕列表中最底部的一个年份的text值
#         # years = self.driver.find_elements_by_class_name("android.widget.TextView")
#         # years_text = years[9].text
#         # # 到列表的最后一个，但没找到
#         # if years_text == "2021"
